<template>
  <div class="profile-page">
    <div class="profile-header">
      <div class="avatar-wrapper" @click="triggerAvatarUpload">
        <el-avatar :size="120" :src="avatarUrl" />
        <div class="avatar-tip">点击更换头像</div>
        <input ref="avatarInput" type="file" accept="image/*" style="display:none" @change="handleAvatarChange" />
      </div>
      <div class="profile-name">{{ user.username }}</div>
      <div class="profile-status">
        <span class="status-dot online"></span> 在线
      </div>
      <div class="profile-role">
        <el-tag type="danger">超级管理员</el-tag>
      </div>
    </div>
    <el-divider />
    <div class="profile-info-card">
      <div class="info-title">
        <el-icon><User /></el-icon>
        <span>基本信息</span>
      </div>
      <div class="info-content">
        <div class="info-item">
          <el-icon><Message /></el-icon>
          <span>邮箱</span>
          <span class="info-value">{{ user.email }}</span>
        </div>
        <div class="info-item">
          <el-icon><Phone /></el-icon>
          <span>电话</span>
          <span class="info-value">{{ user.phone }}</span>
        </div>
      </div>
    </div>
    <div class="profile-actions">
      <el-button type="primary" @click="editing = true"><el-icon><Edit /></el-icon>编辑资料</el-button>
      <el-button type="success" @click="triggerAvatarUpload"><el-icon><Camera /></el-icon>更换头像</el-button>
    </div>
    <el-dialog v-model="editing" title="编辑资料" width="400px">
      <el-form :model="user" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="user.username" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="user.email" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="user.phone" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelEdit">取消</el-button>
        <el-button type="primary" @click="saveInfo">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getUserList, uploadAvatar,getUserAvatarInfo,updateUser,getUserDetail } from '@/api/user'
import { getTokenUserInfo } from '@/utils/auth'

import avatarImg from '@/assets/avatar.png'
import { User, Message, Phone, Edit, Camera } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

// 是否处于编辑资料弹窗状态
const editing = ref(false)
// 当前用户信息
const user = ref({
  avatar: avatarImg,
  username: '',
  email: '',
  phone: '',
})
//头像地址
let avatarUrl=ref(null)
// 备份用户信息，用于取消编辑时还原
const oldUser = ref({ ...user.value })
// 头像上传 input 的 ref
const avatarInput = ref(null)
// 获取用户store
const userStore = useUserStore()

// 页面挂载时，获取当前用户信息（通过用户列表接口筛选当前用户）
onMounted(async () => {
  const tokenUser = getTokenUserInfo()
  if (tokenUser && tokenUser.userId) {
    const res = await getUserList({})
    if (res && res.data) {
      const userData = res.data.users || res.data
      let myInfo = null
      if (Array.isArray(userData)) {
        myInfo = userData.find(u => u.id === tokenUser.userId || u.userId === tokenUser.userId)
      }
      if (myInfo) {
        user.value = {
          avatar: myInfo.avatar ? `/api/users/avatar-file/${myInfo.avatar}` : avatarImg,
          username: myInfo.userName || myInfo.username || '',
          email: myInfo.email || '',
          phone: myInfo.phoneNumber || myInfo.phone || '',
        }
        oldUser.value = { ...user.value }
      }
    }
 
   await getAvatarUrl(tokenUser.userId)

    
  }
})

//获取头像
let getAvatarUrl=async (userId)=>{
  let {data}=await getUserAvatarInfo(userId)
    console.log(data.avatarUrl);
    avatarUrl.value=`http://api-rag.monkeymeerkat.cn${data.avatarUrl}`
    // 同时更新store中的头像
    userStore.setUserAvatar(avatarUrl.value)
}

// 保存资料（可对接后端保存接口）
const saveInfo =async () => {
  editing.value = false
  oldUser.value = { ...user.value }



let users=JSON.parse(localStorage.getItem("userInfo"))
let res=  await updateUser(users.id,{
    UserName:oldUser.value.username,
    Email:oldUser.value.email,
    phoneNumber:oldUser.value.phone
  })
  console.log(res);
  await getUserDetail(users.id)


  // TODO: 保存到后端
}
// 取消编辑，还原为原始数据
const cancelEdit = () => {
  user.value = { ...oldUser.value }
  editing.value = false
}
// 触发头像上传 input
const triggerAvatarUpload = () => {
  avatarInput.value && avatarInput.value.click()
}
// 处理头像文件选择并上传
const handleAvatarChange = async (e) => {
  const file = e.target.files[0]
  console.log(file);
  
  if (file) {
    // 本地预览
    user.value.avatar = URL.createObjectURL(file)
    console.log(user.value.avatar);
    
    const tokenUser = getTokenUserInfo()
    if (tokenUser && tokenUser.userId) {
      try {
         await uploadAvatar(tokenUser.userId, file)
        await getAvatarUrl(tokenUser.userId)
        
        // 处理后端返回的头像文件名，拼接为可访问的URL
        if (res && res.data && res.data.avatar) {
          user.value.avatar = `/api/users/avatar-file/${res.data.avatar}`
        }
      } catch (err) {
        // 可加提示
      }
    }
  }
}
</script>

<style scoped>
.profile-page {
  max-width: 700px;
  margin: 40px auto;
  background: #fff;
  border-radius: 24px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.06);
  padding: 40px 32px 32px 32px;
}
.profile-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 24px;
}
.avatar-wrapper {
  position: relative;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.avatar-tip {
  font-size: 14px;
  color: #888;
  margin-top: 8px;
}
.profile-name {
  font-size: 2rem;
  font-weight: bold;
  margin-top: 16px;
  margin-bottom: 8px;
}
.profile-status {
  color: #27c24c;
  font-size: 16px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}
.status-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: #27c24c;
  margin-right: 4px;
}
.profile-role {
  margin-bottom: 12px;
}
.profile-info-card {
  background: #f8fafc;
  border-radius: 16px;
  padding: 24px 24px 12px 24px;
  margin-bottom: 24px;
}
.info-title {
  font-size: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
}
.info-content {
  display: flex;
  gap: 32px;
  flex-wrap: wrap;
}
.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  background: #fff;
  border-radius: 8px;
  padding: 12px 20px;
  margin-bottom: 12px;
  min-width: 220px;
}
.info-value {
  font-weight: 500;
  margin-left: 8px;
}
.profile-actions {
  display: flex;
  gap: 24px;
  justify-content: center;
  margin-top: 24px;
}
</style> 